import { defineStore } from 'pinia'
import { storage } from '../../utils/storage'
import { loginByJson } from "../../api/login"
import Cookies from 'js-cookie'

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useUserStore = defineStore('userStore', {
  // 推荐使用 完整类型推断的箭头函数
  state: () => {
    return {
      Token: storage.get('Auth-Token') || '',
      uid: 1,
      username: '',
      isLoggedIn: false,
      monitor: true
    }
  },
  actions: {
    changeMonitor(e:any) {
      const store:any = this
      return new Promise((resolve:any) => {
         store.monitor = e
         console.log(store.monitor)
         resolve()
      })
    },
    login(data:any) {
      const store:any = this
      return new Promise((resolve, reject) => {
        loginByJson(data)
          .then((response:any) => {
            const result = response.data
            store.Token = result.token
            store.username = result.name
            storage.set('Auth-Token', result.token)
            resolve(response)
          })
          .catch(reject)
      })

    },
    /**
   * 清除用户storage信息
   */
    removeLogout() {
      // window.location.reload();
      const store:any = this
      return new Promise((resolve:any) => {
          storage.remove('Auth-Token')
          storage.remove('baijiahao-Token')
          window.electron.ipcRenderer.invoke('clear-all-cookies').then((result) => {
            console.log(result)
          })
          store.Token = ''
          store.username = ''
          store.isLoggedIn = false
          // 清空所有 Cookie
          const allCookies = Cookies.get();
          for (const cookieName in allCookies) {
            if (allCookies.hasOwnProperty(cookieName)) {
              Cookies.remove(cookieName, { path: '/' }); // 确保路径与设置时一致
            }
          }
          resolve()
      })
    },

    resetToken() {
      const store:any = this
      return new Promise((resolve:any) => {
        storage.remove('Auth-Token')
        storage.remove('baijiahao-Token')
        store.Token = ''
        store.username = ''
        store.isLoggedIn = false
        resolve()
      })
    }
  },
  getters: {},
  persist: {
    // 开启持久化
    enabled: true,
    // 选择存储方式和内容
    // strategies: [
    //   {
      //   key: 'token',
    //     storage: localStorage, //默认走session
    //     paths: ['token']
    //   }
    // ]
  }
})
